package com.gl.order.security.handle;

import com.gl.order.commom.ResultBean;
import com.gl.order.commom.util.JwtTokenUtils;
import com.gl.order.commom.util.ResponseUtils;
import com.gl.order.config.JwtConfig;
import com.gl.order.security.model.SecurityUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author liangSY
 * @date 2021/6/7 22:24
 * 退出登录成功处理
 */
@Slf4j
public class UserLogoutHandler implements LogoutHandler {

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        log.info("退出登陆操作");
        String token = request.getHeader(JwtConfig.tokenHeader);
        if(StringUtils.isBlank(token)){
            ResponseUtils.responseJson(response, ResultBean.failed("非法操作！"));
            return;
        }
        token = token.substring(JwtConfig.tokenPrefix.length()+1);
        // 移除token
        SecurityUser principal = null;
        if(null != authentication){
            principal = (SecurityUser) authentication.getPrincipal();
        }else{
            principal = JwtTokenUtils.getUserInfo(token);

        }
        JwtTokenUtils.removeToken(principal,token);
        log.info("logout user {} "+principal.getUsername());
        ResponseUtils.responseJson(response, ResultBean.success("logout success"));
    }
}
